package com.fufu.thread;

/**
 * Thread的中断：interrupt()+join()/sleep()
 * @author: BlcakTiger
 * @date: 2023/2/10 13:18
 * @contact: hsf6661@163.com
 */
public class InterruptOfThread {

    public static void main(String[] args) throws InterruptedException {

        Thread t = new MThread();
        //启动t线程
        t.start();
        //使Main线程进入阻塞状态，t线程获取cpu调度
        Thread.sleep(1000);
        //将t线程的中断标志设置为true
        t.interrupt();
        //使Main线程进入等待，等待t线程执行结束
        t.join();
        System.out.println("end");
    }

}

class MThread extends Thread {
    @Override
    public void run() {
        //创建hello线程
        Thread hello = new HelloThread();
        // 启动hello线程
        hello.start();
        try {
            //使t线程进入等待，等待hello线程执行结束
            //因为在main中已经执行了t.interrupt(),将"中断标志"设置为了true，
            //此时join()方法使t线程进入阻塞，这会使"中断标记"立即被清除为"false"，并抛出interruptException
            hello.join();
        } catch (InterruptedException e) {
            System.out.println("interrupted!");
        }
        //设置hello线程的"中断标志"为true
        hello.interrupt();
    }
}

class HelloThread extends Thread {
    @Override
    public void run() {
        int n = 0;
        while (!isInterrupted()) {
            n++;
            System.out.println(n + " hello!");
            try {
                //使hello线程进入阻塞，效果与join、wait...类似
                //因为在t线程的run()方法中已经执行了hello.interrupt(),将"中断标志"设置为了true，
                //此时sleep()方法令hello线程进入阻塞，这会使"中断标记"立即被清除为"false"，并抛出interruptException
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
    }
}
